<template>
  <view class="chat-page">
    <!-- 标题 -->
    <view class="chat-header">
      <text class="chat-title">聊天</text>
    </view>

    <!-- 带放大镜的搜索框 -->
    <view class="search-wrap">
      <view class="search-bar">
        <!-- 放大镜图标 -->
        <image 
          class="search-icon" 
          src="/static/icons/search.png" 
          mode="widthFix"
        ></image>
        <input 
          class="search-input" 
          type="text" 
          placeholder="搜索联系人,公司,聊天记录"
          v-model="searchKeyword"
          @input="handleSearch"
        />
      </view>
    </view>

    <!-- 聊天列表 -->
    <view class="chat-list">
      <view class="list-title">全部</view>
      
      <!-- 加载中状态 -->
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      
      <!-- 空状态 -->
      <view v-if="!loading && chatList.length === 0" class="empty">
        <text>暂无聊天记录</text>
      </view>
      
      <block v-for="(item, index) in chatList" :key="item.hrId">
        <navigator 
          class="chat-item" 
          :url="`/pages/zj/UserToHRChat?hrId=${item.hrId}&hrName=${item.hrName}&companyName=${item.company.companyName}&companyId=${item.company.companyId}`"
        >
          <!-- 头像 -->
          <image 
            class="chat-avatar" 
            :src="item.headIcon" 
            mode="aspectFill"
			@error="(e) => handleAvatarError(e, index)"
          ></image>
          <view class="chat-info">
            <view class="info-top">
              <text class="person">{{ item.hrName }}</text>
         <strong></strong>     <text class="company">{{ item.company.companyName }}</text>
            </view>
            <view class="info-bottom">
              <text class="last-message">{{ item.last_message || '点击开始聊天' }}</text>
              <text class="time">{{ formatTime(item.chatTime) }}</text>
            </view>
          </view>
        </navigator>
      </block>
    </view>
	
	<!-- 底部导航栏 -->
	 <u-tabbar v-model="current" :list="list" :mid-button="false" @change="tabChangeHandler"></u-tabbar>
  </view>
</template>

<script>
	import state from '../../store/state';
	import {getChatLists,getHRAndComInfo} from '@/api/chat.js'
export default {
  data() {
    return {
		
		myRole: "user",
		myId: null,
		role: "hr",

		// 用户信息
		userInfo: {
		userId:null,
		  headIcon: '', // 头像
		  username: '',
		},
      chatList: [],        // 完整的聊天列表数据
      rawChatData: [],     // 原始聊天数据（未关联人事信息）
      searchKeyword: '',   // 搜索关键词
      loading: false,      // 加载状态
	  list: [
            {
              iconPath: "home",
              selectedIconPath: "home-fill",
              text: "首页",
              count: 2,
              isDot: true,
              customIcon: false,
		  	pagePath: "/pages/zcy/main"  // 对应首页的页面路径
            },
            {
              iconPath: "chat",
              selectedIconPath: "chat-fill",
              text: "聊天",
              customIcon: false,
		  	pagePath: "/pages/zj/ChatList"  // 对应聊天页面的路径
            },
            {
              iconPath: "account",
              selectedIconPath: "account-fill",
              text: "个人中心",
              count: 23,
              isDot: false,
              customIcon: false,
		  	pagePath: "/pages/zj/PersonalCenter"  // 对应个人中心的页面路径
            },
          ],
          current: 1,  // 默认选中聊天页面
    }
  },
  onLoad() {
	  //加载用户信息
	  this.loadUserInfo();
	   
  },
  methods: {
	  
    // 获取聊天列表数据
     fetchChatData() {
      this.loading = true
	  getChatLists({myRole:this.myRole,role:this.role,myId:this.userInfo.userId})
	  .then(res =>{
		  if(res.code == 200){
			  console.log(res)
			  this.rawChatData = res.data
			   // 2. 批量获取人事信息
			    this.fetchHrInfoBatch()
			   this.loading = false
		  }
	  })   
    },
    
    // 批量获取人事信息
     fetchHrInfoBatch() {
      // 提取所有不重复的hrId
      const hrIds = [...new Set(this.rawChatData.map(item => item.yourId))]
      console.log(hrIds)
      if (hrIds.length === 0) {
        this.chatList = []
        return
      }     
		  getHRAndComInfo({hrId: hrIds})
		  .then(res =>{
			  if(res.code === 200){
				  console.log(res)
				  // 合并聊天数据和人事信息
				  this.chatList = res.data
			  }
		  })
    },
    
    // 搜索处理
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        // 如果搜索关键词为空，显示全部数据
        this.fetchHrInfoBatch()
        return
      }
      
      // 根据关键词过滤数据
      const filtered = this.rawChatData.filter(item => {
        // 这里假设我们已经有了person, company等信息
        // 实际应用中可能需要先缓存完整数据再过滤
        const hrInfo = this.chatList.find(c => c.id === item.id) || {}
        const keyword = this.searchKeyword.toLowerCase()
        return hrInfo.person.toLowerCase().includes(keyword) ||
               hrInfo.company.toLowerCase().includes(keyword) ||
               (item.last_message && item.last_message.toLowerCase().includes(keyword))
      })
      
      // 转换为展示数据
      this.chatList = filtered.map(chat => {
        const hrInfo = this.chatList.find(c => c.id === chat.id) || {}
        return {
          ...chat,
          person: hrInfo.person || '未知联系人',
          company: hrInfo.company || '未知公司',
          position: hrInfo.position || '未知职位',
          avatar: hrInfo.avatar || ''
        }
      })
    },
    // 加载用户信息（打开页面时获取）
    loadUserInfo() {
    	 if (!state.userInfo) {
    	    setTimeout(() => {
    	          this.loadUserInfo(); // 执行你的方法
    	        }, 2000);
    				return;
    	  }
    		  this.userInfo.username = state.userInfo.username;
    		  this.userInfo.headIcon = state.userInfo.headIcon;
    		  this.userInfo.userId = state.userInfo.userId;
			  this.fetchChatData();
    },
	// 重连WebSocket

	    
	    // 发送WebSocket消息
	    sendWebSocketMessage(data) {
	      if (this.isWebSocketConnected && this.webSocket) {
	        try {
	          this.webSocket.send(JSON.stringify(data));
	        } catch (e) {
	          console.error('发送WebSocket消息失败:', e);
	        }
	      } else {
	        console.warn('WebSocket未连接，无法发送消息');
	      }
	    },
	// 头像加载失败时，强制使用默认头像
	  handleAvatarError(e, index) {
	   this.chatList[index].headIcon = "/static/avatar/avatar.png";
	  },
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''
      
      const date = new Date(timeStr)
      const now = new Date()
      
      // 今天
      if (date.toDateString() === now.toDateString()) {
        return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      }
      
      // 今年
      if (date.getFullYear() === now.getFullYear()) {
        return `${date.getMonth() + 1}-${date.getDate()}`
      }
      
      // 往年
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    },
    
    // 导航栏跳转
    tabChangeHandler(index) {
      const pagePath = this.list[index].pagePath;
      // 必须用 switchTab 跳转 tabBar 页面
      uni.switchTab({
        url: pagePath,
        fail: (err) => {
          console.error("跳转失败：", err);
        }
      });
    },
  }
}
</script>

<style scoped>
/* 页面基础样式 */
.chat-page {
  padding: 15px;
  background-color: #fff;
  min-height: 100vh;
}

/* 标题 */
.chat-header {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 12px;
}

/* 搜索框外层容器：控制水平居中+宽度 */
.search-wrap {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

/* 搜索框容器：带边框+圆角 */
.search-bar {
  display: flex;
  align-items: center;
  width: 80%; /* 可调整为 70%/90% 等 */
  height: 36px;
  border: 1px solid #ddd;
  border-radius: 20px;
  overflow: hidden;
  background-color: #f8f8f8;
}

/* 放大镜图标：固定尺寸+间距 */
.search-icon {
  width: 18px;
  height: 18px;
  margin: 0 8px 0 12px;
}

/* 搜索输入框：自适应+无边框 */
.search-input {
  flex: 1;
  height: 100%;
  font-size: 14px;
  border: none;
  outline: none;
  background-color: transparent;
}

/* 聊天列表标题 */
.list-title {
  font-size: 16px;
  font-weight: bold;
  margin: 10px 0;
  color: #333;
}

/* 加载中和空状态样式 */
.loading, .empty {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

/* 聊天条目：flex 布局 */
.chat-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

/* 头像：圆形+固定尺寸 */
.chat-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 10px;
}

/* 右侧信息区 */
.chat-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 顶部信息行 */
.info-top {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
  flex-wrap: wrap;
}

/* 底部信息行 */
.info-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 文字样式区分 */
.person {
  font-weight: bold;
  color: #333;
  margin-right: 4px;
}
.company {
  color: #666;
  font-size: 14px;
}
.position {
  color: #666;
  font-size: 14px;
}
.last-message {
  color: #666;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

/* 时间样式：灰色+小字号 */
.time {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}
</style>
